package com.yhb.service.impl;

import com.baidu.aip.face.AipFace;
import com.yhb.conf.ResultCode;
import com.yhb.service.RealNameAuthenticationService;
import lombok.extern.log4j.Log4j;
import me.edzh.spring.bootstrap.common.GlobalPropertiesConfigurer;
import me.edzh.spring.bootstrap.service.ObjectiveStorageService;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Log4j
@Service
public class BaiduRealNameAuthenticationServiceImpl implements RealNameAuthenticationService {

    @Autowired
    private ObjectiveStorageService ossServiceImpl;

    private AipFace client = new AipFace(GlobalPropertiesConfigurer.getProperty("baiduai.appid"), GlobalPropertiesConfigurer.getProperty("baiduai.ak"), GlobalPropertiesConfigurer.getProperty("baiduai.sk"));
    private static HashMap<String, String> personVerifyOptions = new HashMap<>();
    static {
        personVerifyOptions.put("quality_control", "NORMAL");
        personVerifyOptions.put("liveness_controll", "NORMAL");
    }

    @PostConstruct
    private void init() {

    }

    @Override
    public Long checkRealName(String name, String idNumber, String imageUrl) {
        imageUrl = ossServiceImpl.signUrl(imageUrl);
        JSONObject res = client.personVerify(imageUrl, "URL", idNumber, name, personVerifyOptions);
        log.info(res.toString());
        JSONObject result = res.optJSONObject("result");
        if (result != null) {
            double score = result.optDouble("score", 80);
            if (score < 90) {
                throw new ServiceException(ResultCode.ERROR_REAL_NAME_AUTHENTICATION_ERR, "实名认证失败: 照片和本人匹配度差");
            }

            return (long)(score);
        }

        throw new ServiceException(ResultCode.ERROR_INTERNAL_DATA_CODE, "实名认证失败!");
    }

}
